package com.lmxdawn.api.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.lmxdawn.api.common.res.BaseResponse;
import com.lmxdawn.api.common.util.IdWorker;
import com.lmxdawn.api.common.util.ResultVOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author huangyubin
 * @since 2024-07-03
 */
@RestController
@RequestMapping("/admin/file")
public class FileController {

    @Resource
    private IdWorker idWorker;
    private static final String UPLOAD_DIR = "/upload";
    private static final String DOMAIN = "http://www.5808d.com/img/";

    @PostMapping("/upload")
    public BaseResponse sale(@RequestParam("file") MultipartFile file,
                             @RequestParam(value = "path", required = false) String path) {

        if (file.isEmpty()) {
            return ResultVOUtils.error(500, "请选择要上传的文件");
        }
        try {
            // 创建上传目录
            String date = DateUtil.format(DateUtil.date(), "yyyyMMdd");
            String baseUrl = UPLOAD_DIR + (StrUtil.isNotBlank(path) ? (File.separator + path) : "") + File.separator + date;
            File dir = new File(baseUrl);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 保存文件
            long l = idWorker.nextId();
            File destinationFile = new File(dir, l + "."
                    + FileUtil.getSuffix(file.getOriginalFilename()));
            file.transferTo(destinationFile);
            return ResultVOUtils.success(DOMAIN + (StrUtil.isNotBlank(path) ? path + "/" : "") + date + "/" + destinationFile.getName());
        } catch (IOException e) {
            return ResultVOUtils.error(500, "文件上传失败: " + e.getMessage());
        }
    }

}
